package com.ant.storage.service.impl;
import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultPage;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.AllocationMapper;
import com.ant.storage.pojo.*;
import com.ant.storage.service.*;
import com.ant.storage.utils.DingDingUtil;
import com.ant.storage.utils.NullInspectUtil;
import com.ant.storage.common.PageRecv;
import com.ant.storage.common.ResultVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taobao.api.ApiException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AllocationServiceImpl extends ServiceImpl<AllocationMapper,Allocation> implements IAllocationService {

    @Autowired(required = false)
    AllocationMapper allocationMapper;

    @Autowired
    IDingUserDetailsService dingUserDetailsService;

    @Autowired
    ICityService cityService;

    @Autowired
    IWarehouseService warehouseService;

    @Autowired
    IUserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAllocation(Allocation allocation) throws NoSuchFieldException {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        allocation.setAllocation_time(simpleDateFormat.format(date));
        allocation.setAllocation_type("1");
        String str01 = NullInspectUtil.ClassnullInspect(allocation,"allocation_id","allocation_remarks","process_instance_id","approver_name","approver_phone","cc_list_name","cc_list_phone","staff_userid","staff_dept_id","approver_userid","cc_list_userid","supply_city","supply_dept","extract_city","extract_dept","start_time","end_time");
        if(str01 != null){
            NullInspectUtil.myAnnotationError(allocation,str01);
        }
        try{
            if(!this.save(allocation)){
                throw new AntException(ResultCode.SQL_INSERT_ERR);
            }
            for (AllocationAndCommodity allocationAndCommodity:allocation.getAllocationAndCommodity()) {
                if(allocationAndCommodity.getCommodity_allocation_quantity() == null||allocationAndCommodity.getCommodity_allocation_quantity()<=0){
                    throw new AntException(ResultCode.GOOD_NUMBER_ERROR);
                }
                if(allocationAndCommodity.getCommodity().getCommodityId() == null||allocationAndCommodity.getCommodity().getCommodityId()<=0){
                    throw new AntException(ResultCode.GOOD_ID_ERROR);
                }
                allocationMapper.addAllocationAndCommodity(allocation.getAllocation_id(),
                        allocationAndCommodity.getCommodity().getCommodityId(),allocationAndCommodity.
                                getCommodity_allocation_quantity());
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo updateAllocation(Allocation allocation) throws NoSuchFieldException {
        if(allocation.getAllocation_id() == null || allocation.getAllocation_id().equals("")||allocation.getAllocation_id() <=0){
            throw new AntException(ResultCode.ALLOCATION_ID_ERROR);
        }
        if(allocation.getAllocationAndCommodity() == null){
            throw new AntException(ResultCode.GOOD_NULL_ERROR);
        }
        //删除中间表数据
        allocationMapper.removeAllocationAndCommodity(allocation.getAllocation_id());
        for (AllocationAndCommodity allocationAndCommodity:allocation.getAllocationAndCommodity()) {
            if(allocationAndCommodity.getCommodity().getCommodityId() == null||allocationAndCommodity.getCommodity().getCommodityId()<=0){
                throw new AntException(ResultCode.GOOD_ID_ERROR);
            }
            if(allocationAndCommodity.getCommodity_allocation_quantity() == null||allocationAndCommodity.getCommodity_allocation_quantity()<=0){
                throw new AntException(ResultCode.GOOD_NUMBER_ERROR);
            }
            allocationMapper.addAllocationAndCommodity(allocation.getAllocation_id(), allocationAndCommodity.getCommodity().getCommodityId(),allocationAndCommodity.getCommodity_allocation_quantity());
        }
        //更新调拨单
        UpdateWrapper<Allocation>updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("allocation_id",allocation.getAllocation_id());
        this.update(allocation,updateWrapper);
        return ResultVo.success("ok");
    }

    @SneakyThrows
    @Override
    @Transactional
    public ResultVo addDingDing(Allocation allocation) throws ApiException {
        User user = userService.queryUserId(allocation.getStaff_name(),allocation.getStaff_phone());
        allocation.setStaff_userid(user.getUserid());
        allocation.setStaff_dept_id(user.getDept_id());
        User user01 = userService.queryUserId(allocation.getApprover_name(),allocation.getApprover_phone());
        allocation.setApprover_userid(user01.getUserid());
        User user02 = userService.queryUserId(allocation.getCc_list_name(),allocation.getCc_list_phone());
        allocation.setCc_list_userid(user02.getUserid());
       // System.out.println(allocation);
        String str01 = NullInspectUtil.ClassnullInspect(allocation,"allocation_remarks","process_instance_id","supply_dept","extract_city","extract_dept","start_time","end_time");
        if(str01 != null){
            NullInspectUtil.myAnnotationError(allocation,str01);
        }
        String access_token = allocationMapper.queryToken();
        String process_instance_id;
        try{
            process_instance_id = DingDingUtil.OldExamineAndApprove(allocation,access_token);
        }catch (AntException e){
            if (e.getErrorCode() == 88) {
                access_token = DingDingUtil.obtainToken();
                allocationMapper.addToken(access_token);
                process_instance_id = DingDingUtil.OldExamineAndApprove(allocation,access_token);
            }else{
                throw e;
            }
        }
        allocation.setProcess_instance_id(process_instance_id);
        UpdateWrapper<Allocation>updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("allocation_id",allocation.getAllocation_id());
        allocation.setAllocation_type("2");
        System.out.println(allocation);
        this.update(allocation,updateWrapper);
//        //获取申请人电话号码
//        String staff_phone = allocation.getStaff_phone();
//        //获取审批人电话号码
//        String approver_phone = allocation.getApprover_phone();
//        //获取抄送人电话号码
//        String cc_list_phone = allocation.getCc_list_phone();
//        if(!Pattern.matches("^0?(13|14|15|18)[0-9]{9}$", staff_phone)){
//            throw new AntException(ResultCode.STAFF_PHONE_NULL);
//        }
//        if(!Pattern.matches("^0?(13|14|15|18)[0-9]{9}$", approver_phone)){
//            throw new AntException(ResultCode.APPROVER_PHONE_NULL);
//        }
//        if( !Pattern.matches("^0?(13|14|15|18)[0-9]{9}$", cc_list_phone)){
//            throw new AntException(ResultCode.CC_LIST_PHONE_NULL);
//        }
//        QueryWrapper<DingUserDetails>queryWrapper0 = new QueryWrapper<>();
//        queryWrapper0.eq("phone",staff_phone);
//        DingUserDetails dingUserDetails = dingUserDetailsService.getOne(queryWrapper0);
//        QueryWrapper<DingUserDetails>queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("phone",approver_phone);
//        DingUserDetails dingUserDetails1 = dingUserDetailsService.getOne(queryWrapper1);
//        QueryWrapper<DingUserDetails>queryWrapper2 = new QueryWrapper<>();
//        queryWrapper2.eq("phone",cc_list_phone);
//        DingUserDetails dingUserDetails2 = dingUserDetailsService.getOne(queryWrapper2);
//        String access_token = allocationMapper.queryToken();
//        if(dingUserDetails == null) {
//            dingUserDetails = new DingUserDetails();
//            String userid;
//            try{
//                userid = DingDingUtil.queryUserId(staff_phone, access_token);
//            }catch (AntException e){
//                if (e.getErrorCode() == 88) {
//                    access_token = DingDingUtil.obtainToken();
//                    allocationMapper.addToken(access_token);
//                    userid = DingDingUtil.queryUserId(staff_phone, access_token);
//                }else{
//                    String str = "申请人"+e.getErrorMsg();
//                    e.setErrorMsg(str);
//                    throw e;
//                }
//            }
//            String str = DingDingUtil.queryUser(userid, access_token);
//            dingUserDetails.setUserid(String.valueOf(JSONObject.parseObject(str).getJSONObject("result").get("userid")));
//            List list = (List) JSONObject.parseObject(str).getJSONObject("result").get("dept_id_list");
//            dingUserDetails.setPhone(Long.parseLong(JSONObject.parseObject(str).getJSONObject("result").get("mobile").toString()));
//            dingUserDetails.setName(String.valueOf(JSONObject.parseObject(str).getJSONObject("result").get("name")));
//            dingUserDetails.setDept_id((Integer) list.get(list.size() - 1));
//            dingUserDetails.setUp_dept_id((Integer) list.get(list.size() - 2));
//            UpdateWrapper<DingUserDetails>updateWrapper0 = new UpdateWrapper<>();
//            updateWrapper0.eq("phone",dingUserDetails.getPhone());
//            dingUserDetailsService.saveOrUpdate(dingUserDetails,updateWrapper0);
//        }
//        if (dingUserDetails1 == null) {
//            dingUserDetails1 = new DingUserDetails();
//            String userid;
//            try{
//                userid = DingDingUtil.queryUserId(approver_phone, access_token);
//            }catch (AntException e){
//                if (e.getErrorCode() == 88) {
//                    access_token = DingDingUtil.obtainToken();
//                    allocationMapper.addToken(access_token);
//                    userid = DingDingUtil.queryUserId(approver_phone, access_token);
//                }else{
//                    String str = "审批人"+e.getErrorMsg();
//                    e.setErrorMsg(str);
//                    throw e;
//                }
//            }
//            String str = DingDingUtil.queryUser(userid,access_token);
//            dingUserDetails1.setUserid(String.valueOf(JSONObject.parseObject(str).getJSONObject("result").get("userid")));
//            List list = (List)JSONObject.parseObject(str).getJSONObject("result").get("dept_id_list");
//            dingUserDetails1.setPhone(Long.parseLong(JSONObject.parseObject(str).getJSONObject("result").get("mobile").toString()));
//            dingUserDetails1.setName(String.valueOf(JSONObject.parseObject(str).getJSONObject("result").get("name")));
//            dingUserDetails1.setDept_id((Integer) list.get(list.size()-1));
//            dingUserDetails1.setUp_dept_id((Integer) list.get(list.size()-2));
//            UpdateWrapper<DingUserDetails>updateWrapper01 = new UpdateWrapper<>();
//            updateWrapper01.eq("phone",dingUserDetails1.getPhone());
//            dingUserDetailsService.saveOrUpdate(dingUserDetails1,updateWrapper01);
//        }
//        if (dingUserDetails2 == null) {
//            dingUserDetails2 = new DingUserDetails();
//            String userid;
//            try{
//                userid = DingDingUtil.queryUserId(cc_list_phone, access_token);
//            }catch (AntException e){
//                if (e.getErrorCode() == 88) {
//                    access_token = DingDingUtil.obtainToken();
//                    allocationMapper.addToken(access_token);
//                    userid = DingDingUtil.queryUserId(cc_list_phone, access_token);
//                }else{
//                    String str = "抄送人"+e.getErrorMsg();
//                    e.setErrorMsg(str);
//                    throw e;
//                }
//            }
//            String str = DingDingUtil.queryUser(userid,access_token);
//            dingUserDetails2.setUserid(String.valueOf(JSONObject.parseObject(str).getJSONObject("result").get("userid")));
//            List list = (List)JSONObject.parseObject(str).getJSONObject("result").get("dept_id_list");
//            dingUserDetails2.setPhone(Long.parseLong(JSONObject.parseObject(str).getJSONObject("result").get("mobile").toString()));
//            dingUserDetails2.setName(String.valueOf(JSONObject.parseObject(str).getJSONObject("result").get("name")));
//            dingUserDetails2.setUp_dept_id((Integer) list.get(list.size()-2));
//            dingUserDetails2.setDept_id((Integer) list.get(list.size()-1));
//            UpdateWrapper<DingUserDetails>updateWrapper02 = new UpdateWrapper<>();
//            updateWrapper02.eq("phone",dingUserDetails2.getPhone());
//            dingUserDetailsService.saveOrUpdate(dingUserDetails2,updateWrapper02);
//        }
//        List <DingUserDetails>list = new ArrayList<>();
//        list.add(dingUserDetails);
//        list.add(dingUserDetails1);
//        list.add(dingUserDetails2);
////        String supply_city = cityService.idQuery(allocation.getAllocation_supply_city_id());
////        String supply_dept = cityService.idQuery(allocation.getAllocation_supply_dept_id());
////        String extract_city = cityService.idQuery(allocation.getAllocation_extract_city_id());
////        String extract_dept = cityService.idQuery(allocation.getAllocation_extract_dept_id());
////        allocation.getSupply_city().setName(supply_city);
////        allocation.getSupply_dept().setName(supply_dept);
////        allocation.getExtract_city().setName(extract_city);
////        allocation.getExtract_dept().setName(extract_dept);
//        String process_instance_id;
//        try{
//            process_instance_id = DingDingUtil.OldExamineAndApprove(list,allocation,access_token);
//        }catch (AntException e){
//            if (e.getErrorCode() == 88) {
//                access_token = DingDingUtil.obtainToken();
//                allocationMapper.addToken(access_token);
//                process_instance_id = DingDingUtil.OldExamineAndApprove(list,allocation,access_token);
//            }else{
//                throw e;
//            }
//        }
//        allocation.setProcess_instance_id(process_instance_id);
//        UpdateWrapper<Allocation>updateWrapper = new UpdateWrapper<>();
//        updateWrapper.eq("allocation_id",allocation.getAllocation_id());
//        allocation.setAllocation_type("2");
//        this.update(allocation,updateWrapper);
        return ResultVo.success("提交成功");
    }

    @Override
    public ResultVo queryAllocationMessage(Integer allocation_id) {
        Allocation allocation = allocationMapper.queryAllocationMessage(allocation_id);
        allocation.getSupply_city().setName(cityService.idQuery(allocation.getAllocation_supply_city_id()));
        allocation.getSupply_dept().setName(cityService.idQuery(allocation.getAllocation_supply_dept_id()));
        allocation.getExtract_city().setName(cityService.idQuery(allocation.getAllocation_extract_city_id()));
        allocation.getExtract_dept().setName(cityService.idQuery(allocation.getAllocation_extract_dept_id()));
        return ResultVo.success("ok",allocation);
    }

    @Override
    public ResultPage queryAllocation(PageRecv<Allocation> pageRecv) {
        Map map = new HashMap<>();
        if (!(pageRecv.getData()==null)){
            map = NullInspectUtil.ClassChangeMapNotNull(pageRecv.getData());
        }
        Integer page = (pageRecv.getCurrentPage()-1)*pageRecv.getPageSize();
        Integer limit = pageRecv.getCurrentPage()*pageRecv.getPageSize();
        List<Allocation> list = allocationMapper.queryAllocation(page,limit,map);
        for (Allocation allocation:list) {
            allocation.getSupply_city().setName(cityService.idQuery(allocation.getAllocation_supply_city_id()));
            allocation.getSupply_dept().setName(cityService.idQuery(allocation.getAllocation_supply_dept_id()));
            allocation.getExtract_city().setName(cityService.idQuery(allocation.getAllocation_extract_city_id()));
            allocation.getExtract_dept().setName( cityService.idQuery(allocation.getAllocation_extract_dept_id()));
        }
        Integer count = allocationMapper.countAllocation(map);
        return ResultPage.success("查询成功",list,count);
    }


    @Override
    public ResultVo revokeAllocation(String process_instance_id) throws ApiException {
        String access_token = allocationMapper.queryToken();
        UpdateWrapper<Allocation> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("process_instance_id",process_instance_id);
        Allocation allocation = new Allocation();
        allocation.setAllocation_type("5");
        try{
            DingDingUtil.examineAndApproveRevoke(access_token,process_instance_id);
            this.update(allocation,updateWrapper);
        }catch (AntException e){
            if (e.getErrorCode() == 88) {
                access_token = DingDingUtil.obtainToken();
                allocationMapper.addToken(access_token);
                DingDingUtil.examineAndApproveRevoke(access_token,process_instance_id);
                this.update(allocation,updateWrapper);
            }else{
                throw e;
            }
        }
        return ResultVo.success("ok");
    }

    public static void main(String[] args) throws ApiException {
        String access_token = DingDingUtil.obtainToken();
       // System.out.println(access_token);
    }
}
